package cn.edu.xmist.supermarket.xxh.controller;

import cn.edu.xmist.supermarket.xxh.entity.ChanpinPO;
import cn.edu.xmist.supermarket.xxh.entity.GongyingshangPO;
import cn.edu.xmist.supermarket.xxh.service.ChanpinService;
import cn.edu.xmist.supermarket.xxh.service.GongyingshangService;
import cn.edu.xmist.supermarket.xxh.util.ObjtoLayJson;
import cn.edu.xmist.supermarket.xxh.config.Vars;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 供应商
 */
@RestController
@RequestMapping("/gongyingshang")
public class GongyingshangController {

  public static final String[] COLUMNS = {"id", "supplierCode", "supplierName", "supplierBrand"};

  @Autowired private GongyingshangService gongyingshangService;
  @Autowired private ChanpinService wareService;

  @RequestMapping("/list")
  public String list(Integer page, Integer limit) throws Exception {
    List<GongyingshangPO> list = gongyingshangService.list();
    return ObjtoLayJson.ListtoJson(list, COLUMNS);
  }

  @RequestMapping("/saveOrUpdate")
  public String saveOrUpdate(GongyingshangPO supplier) {
    if (supplier.getId() == null) {
      QueryWrapper<GongyingshangPO> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("supplier_code", supplier.getSupplierCode());
      List<GongyingshangPO> list = gongyingshangService.list(queryWrapper);
      if (list.size() > 0) {
        return Vars.FAILURE;
      }
    }
    gongyingshangService.saveOrUpdate(supplier);
    return Vars.SUCCESS;
  }

  @RequestMapping("/deleteById")
  public String deleteById(Long id) {
    GongyingshangPO supplier = gongyingshangService.getById(id);
    QueryWrapper<ChanpinPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("supplier_code", supplier.getSupplierCode());
    List<ChanpinPO> list = wareService.list(queryWrapper);
    if (list.size() > 0) {
      return Vars.FAILURE;
    }
    gongyingshangService.removeById(id);
    return Vars.SUCCESS;
  }
}
